﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using Microhard.Core;
using FluentValidation.Results;
using Microhard.Plat.CompanyChargingMng.Models;
using Microhard.Plat.CompanyChargingMng.Msg;
using Microhard.Plat.CompanyChargingMng.Sys;
using Microhard.Plat.CompanyChargingMng.Interfaces;

namespace Microhard.Plat.CompanyChargingMng.Validators
{
    public class CompanyModelValidator : AbstractValidator<CompanyModel>
    {
        public CompanyModelValidator()
        {
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.Name).NotEmpty().WithMessage(CompanyMsg.NeedName).When(r => r.CompanyID == Guid.Empty);
                RuleFor(u => u.Name).Length(1, 50).WithMessage(CompanyMsg.MaxNameLength).When(r => r.CompanyID == Guid.Empty);

                Custom(u =>
                {
                    if (u.CompanyType == (int)CompanyType.Sub && u.Com_CompanyID == Guid.Empty)
                    {
                        return new ValidationFailure("Com_CompanyID", CompanyMsg.HeaderCanNotSub);
                    }

                    ICompany icompany = IoC.Resolve<ICompany>();
                    if (icompany.IsDuplicate(u))
                    {
                        return new ValidationFailure("Name", CompanyMsg.DuplicateName);
                    }
                    return null;
                });
            });

            RuleSet("Update", () =>
            {
                RuleFor(u => u.Name).NotEmpty().WithMessage(CompanyMsg.NeedName);
                RuleFor(u => u.Name).Length(1, 50).WithMessage(CompanyMsg.MaxNameLength);

                Custom(u =>
                {
                    ICompany icompany = IoC.Resolve<ICompany>();
                    var cmp = icompany.GetModelByID(u.CompanyID);
                    if (cmp.Name != u.Name && icompany.IsDuplicate(u))
                    {
                        return new ValidationFailure("Name", CompanyMsg.DuplicateName);
                    }
                    return null;
                });
            });
        }
    }
}
